const {setUrl} = require('../utils/util')
const ApiConfig = require('./api-config')
let instance = null



class ApiConfigRequest {
  /**
   *  @type {ApiConfigRequest}
   */

  constructor(){
   this.apiConfig={}
  }
  
  // 设置当前使用的请求服务
  setRequests(requests){
    this.requests = requests
    return this
  }
  getModuleApiNames(moduleName){
	  return this.apiConfig.getModuleApis(moduleName)
  }
  getModuleApis(moduleName){
    let apis = this.apiConfig.getModuleApis(moduleName)
    let apiMap = {}
    let that = this
    for (let key in apis) {
      
      apiMap[key] = function () {
        let url = apis[key].url
        if (apis[key].multiServer) {
          url = apis[key].severUrl + apis[key].url
        }
        let args = Array.prototype.slice.apply(arguments)
  
        let opt = setUrl(url, args)
  
        return that.requests.request({
          url: opt.url,
          method: apis[key].method,
          data: opt.data,
          ...apis[key].extraData
        })
      }
    }
    return apiMap
  }

  
 // 设置api的配置项
  setApiConfig(config){
  const apiConfig = new ApiConfig()
  apiConfig.configLoader(config)
  this.apiConfig = apiConfig
    return this
  }
  static getInstance(){
     if(!instance){
      instance = new ApiConfigRequest()
     }
     return instance
  }
}
module.exports= ApiConfigRequest
